package com.chudy.visual.server.index;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import com.alibaba.druid.util.StringUtils;
import com.chudy.visual.server.pojo.adrirodclient.Sysinfo;
import com.chudy.visual.server.pojo.push.Contentlist;
import com.chudy.visual.server.interceptor.TokenSignInterceptor;
import com.chudy.visual.server.service.*;
import com.jfinal.plugin.activerecord.Record;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;

import com.alibaba.fastjson.JSONObject;
import com.chudy.visual.server.interceptor.CheckReqSignInterceptor;
import com.chudy.visual.server.model.ScContentDelivery;
import com.chudy.visual.server.model.ScDevice;
import com.chudy.visual.server.model.ScLocation;
import com.chudy.visual.server.plugins.TioConst;
import com.chudy.visual.server.utils.SysInfoUtils;
import com.chudy.visual.server.websocket.Const;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;

/**
 * IndexController
 */

@Before(CheckReqSignInterceptor.class)
public class ClientController extends Controller {
	@Inject
	ScLocationService locationService;
	@Inject
	ScDeviceService scDeviceService;
	@Inject
	ScContentService scContentService;
	@Inject
	ScTenantService scTenantService;

	public void index() {
		String text = "Hello.感谢使用触达云屏.";
		renderText(text);
	}

	/**
	 * 初始化租户下的部门
	 */
	@Before(TokenSignInterceptor.class)
	public void initDepartSelectData(){
		Long tenantId = getAttr("tenantId");
		Ret ret = new Ret();
		if(null == tenantId){
			ret.set("mst","参数异常");
		}
		ret = scTenantService.initDepartSelectData(tenantId);
		renderJson(ret
		);
	}


	/**
	 * 获取设备所在位置的基础数据，在设备应用第一次打开时，选择注册
	 * @param device
	 */
	public void getLocationData(ScDevice device) {
		String appid = getPara(0);
		device.setAppid(appid);
		Page<ScLocation> page = locationService.queryByPid(1, PropKit.getInt("location.page.length", 100), "0");
		Page<ScLocation> pagenotop = locationService.queryNotTop(1, 100);
		for (Iterator iterator = page.getList().iterator(); iterator.hasNext();) {
			ScLocation scLocation = (ScLocation) iterator.next();
			List<ScLocation> childs = new ArrayList<ScLocation>();
			ScLocation scLocation_c = new ScLocation();
			scLocation_c.setId(scLocation.getId());
			scLocation_c.setName(scLocation.getName());
			childs.add(scLocation_c);
			for (Iterator iterator2 = pagenotop.getList().iterator(); iterator2.hasNext();) {
				ScLocation cloc = (ScLocation) iterator2.next();
				if (cloc.getPid().equals(scLocation.getId())) {
					childs.add(cloc);
				}
			}
			scLocation.put("_childs", childs);
		}
		renderJson(page);
	}
	//设备注销
	public void clientLogout() {
		ScDevice client = getBean(ScDevice.class, "", true);
		//输入密码，根据设备id和token 注销设备，注销后不属于任何租户
		scDeviceService.deleteById(client.getId());
		Ret ret = new Ret();
		renderJson(ret);
	}


	//设备登录和注册,租户身份校验
	public void clientLogin() {
		String subdomain = getPara("subdomain");
		String pwd = getPara("password");
		Ret ret = new Ret();
		if(StringUtils.isEmpty(subdomain)){
			ret.set("msg","机构代码不能为空");
			renderJson(ret);
		}

		Record r = scTenantService.verifyTenant(subdomain,pwd);
		if(null != r){
			ret.set("data",r);
			ret.set("code","0");
			ScDevice client = getBean(ScDevice.class, "", true);
			ret.delete("code");
			ScDevice d = client;
			d.setIp(getRequest().getRemoteAddr());
			if (SysInfoUtils.PlatForm_adrirod.equalsIgnoreCase(SysInfoUtils.getPlatform(client.getSysinfo()))) {
				// 安卓
				Sysinfo sysinfo = SysInfoUtils.fromAdrirodJson(client.getSysinfo());
				if (null != sysinfo) {
					d.setDeviceName(sysinfo.getDevice().getUuid());
					d.setOsType(SysInfoUtils.PlatForm_adrirod);
					d.setScreenResolution(sysinfo.get_customDevice().getDisplaysize().toString());
				}
			} else {
				// windows
				com.chudy.visual.server.pojo.winclient.Sysinfo sysinfo = SysInfoUtils.fromWinJson(client.getSysinfo());
				if (null != sysinfo) {
					d.setDeviceName(sysinfo.getOs().getDistro());
					d.setOsType(SysInfoUtils.PlatForm_win);
					d.setScreenResolution(sysinfo.get_customDevice().getDisplaysize().toString());
				}
			}

			d.setOnlineStatus(1);//注册时，将设备在线状态初始为 在线
			d.setDelFlag(0);

			//生成租户token
			String token = scTenantService.createToken(d,r.getLong("id"));
			ret.put("token",token);
			d.setToken(token);
			// 保存注册信息
			ScDevice device = scDeviceService.findById(client.getId());
			if (null != device && StrKit.notBlank(device.getId())) {
				d.setId(device.getId());
				d.setUpdateTime(new Date());
				d.update();
			} else {
				d.setCreateTime(new Date());
				d.save();
			}
			ret.put("code", "0");
			renderJson(ret);
		}else{
			ret.set("msg","无效的机构代码");
			renderJson(ret);
		}
	}

	/**
	 * 补充填写设备位置信息
	 */
	@Before(TokenSignInterceptor.class)
	public void updateClientInfo() {
		ScDevice client = getBean(ScDevice.class, "", true);
		Ret ret = new Ret();
		ret.put("code", "0");
		// 保存注册信息
		ScDevice device = scDeviceService.findById(client.getId());
		if (null != device && StrKit.notBlank(device.getId())) {
			device.setLocationId(client.getLocationId());
			device.setLocationName(client.getLocationName());
			device.setLocationRemark(client.getLocationRemark());
			device.setOnlineStatus(1);//注册时，将设备在线状态初始为 在线
			device.update();
			ret.put("code", "0");
			// 查询需要显示的内容
		}
		renderJson(ret);
	}

	/**
	 * 设备启动时获取信息
	 * 1，设备基础配置信息
	 * 2，设备展示内容
	 */
	@Before(TokenSignInterceptor.class)
	public void getClientInfo() {
		String deviceid = getPara("deviceid");
		Ret ret = new Ret();
		Ret data = new Ret();
		ret.put("code", "0");
		// 查询注册信息
		ScDevice device = scDeviceService.findById(deviceid);
		if (null != device && StrKit.notBlank(device.getAppid()) && 1 != device.getDelFlag()) {
			// 获取到了注册信息
			device.setSysinfo(null);
			ret.put("code", "0");
			data.put("device", device);
			try {
				ScContentDelivery c = scContentService.findByDeviceId(deviceid);
				if (null == c) {
					//无发布内容，则展示默认的大屏
					c = scContentService.findByDefault();
				}
				if (null != c) {
					data.put("contentlist", JSONObject.parseArray(c.getContentData(), Contentlist.class));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		} else {
			// 未注册
			ret.put("code", "1000");
		}
		Ret clientSetUp = new Ret();
		ret.put("data", data);
		renderJson(JSONObject.toJSONString(ret));
	}


	/**
	 * 获取在线客户端数量，按照分组显示
	 */
	public void getInfo() {
		int count = 0;
		try {
			count = Tio.getAllChannelContexts(TioConst.appStarter.getServerGroupContext()).getObj().size();
		} catch (NullPointerException ex) {
			ex.printStackTrace();
		}
		int countDevice = 0;
		try {
			countDevice = Tio
					.getChannelContextsByGroup(TioConst.appStarter.getServerGroupContext(), Const.GROUP_DEVICE_ID)
					.getObj().size();
		} catch (NullPointerException ex) {
			ex.printStackTrace();
		}

		Ret ret = new Ret();
		Ret data = new Ret();
		ret.put("code", "0");
		data.put("count", count);
		data.put("countDevice", countDevice);
		ret.put("data", data);
		renderJson(ret);
	}

	/**
	 * 获取在线设备列表
	 */
	public void getClientList() {
		Ret ret = new Ret();
		Ret data = new Ret();
		ret.put("code", "0");
		try {
			org.tio.utils.page.Page<ChannelContext> clients = Tio
					.getPageOfGroup(TioConst.appStarter.getServerGroupContext(), Const.GROUP_DEVICE_ID, 1, 100);
			List<Ret> list = new ArrayList<Ret>();
			for (Iterator iterator = clients.getList().iterator(); iterator.hasNext();) {
				Ret retClient = new Ret();
				ChannelContext context = (ChannelContext) iterator.next();
				retClient.put("bsid", context.getBsId());
				retClient.put("id", context.getId());
				retClient.put("clientid", context.getAttribute("clientid"));
				retClient.put("ip", context.getClientNode().getIp());
				list.add(retClient);
			}
			data.put("list", list);
			data.put("totalRow", clients.getTotalRow());
			data.put("totalPage", clients.getTotalPage());
		} catch (NullPointerException ex) {
			ex.printStackTrace();
		}
		ret.put("data", data);
		renderJson(ret);
	}
}
